﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MyCSharp.HttpUserAgentParser.Providers;
using Volo.Abp.AspNetCore.WebClientInfo;
using Volo.Abp.DependencyInjection;

namespace Jy.Abp.AspNetCore.Mvc;

[Dependency(ReplaceServices = true)]
public class DefaultHttpContextWebClientInfoProvider : HttpContextWebClientInfoProvider
{
    public DefaultHttpContextWebClientInfoProvider(
        ILogger<HttpContextWebClientInfoProvider> logger, 
        IHttpContextAccessor httpContextAccessor, 
        IHttpUserAgentParserProvider httpUserAgentParser) 
        : base(logger, httpContextAccessor, httpUserAgentParser)
    {
    }

    protected override string GetClientIpAddress()
    {
        var httpContext = this.HttpContextAccessor.HttpContext;
        var ip = httpContext?.Request?.Headers["X-Forwarded-For"].FirstOrDefault();
        if (!ip.HasValue())
            ip = base.GetClientIpAddress();
        return ip;
    }
}
